package com.heima.wemedia.interceptor;

import com.heima.common.exception.com.heima.common.util.UserThreadLocal;
import com.heima.model.common.user.ApUser;
import com.heima.model.common.wemedia.pojo.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.heima.common.exception.com.heima.common.util.UserThreadLocal.USER_THREAD_LOCAL;

@Configuration
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if (!StringUtils.isEmpty(userId)){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            USER_THREAD_LOCAL.set(wmUser);
            log.warn("拦截器生效{}",userId);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        USER_THREAD_LOCAL.remove();
    }
}
